import Vue from 'vue'
const state = {
	cartList: [], // 存放购物车列表的数据
	isAllSelected: false,
}

const mutations = {
	// 添加商品列表
	addShopList(state, shopItem) {

		let shopObj = state.cartList.find(item => item.id === shopItem.id);

		if (shopObj) { // 购物车已有该商品，在原有的数量上累加
			shopObj.count += 1
		} else { // 购物车没有该商品，直接加
			// shopItem.count = 1
			// shopItem.isSelected = true;
			// 响应式数据

			Vue.set(shopItem, 'count', 1)
			Vue.set(shopItem, 'isSelected', true)
			state.cartList.push(shopItem)
		}

	},
	// 删除商品列表
	delShopList(state, {
		isAdd,
		index
	}) {
		// 如果是添加，则在基础上加一
		if (isAdd) {
			state.cartList[index].count += 1
		} else {
			// 如果是减少，则先判断商品数量是否大于1
			if (state.cartList[index].count > 1) {
				state.cartList[index].count -= 1

			} else {
				uni.showModal({
					content: '确定要删除该商品吗？',
					success: (res) => {
						console.log(res);
						if (res.confirm) {
							state.cartList.splice(index, 1)
						}
					}
				})

			}
		}

	},

	// 修改是否选中的状态
	changeIsSelectedMutation(state, {
		isSelected,
		index
	}) {
		state.cartList[index].isSelected = isSelected
	},
	// 全选与全不选
	changeAllSelectedMutatiion(state, isSelected) {
		state.cartList.forEach(item => item.isSelected = isSelected)
	},
	// 删除订单列表
	// changeOrderListMutation(state,newCartList) {
	// 	newCartList = []
	// }
}

const actions = {}

const getters = {
	// 计算全选与全不选
	isAllSelected(state) {
		return state.cartList.every(item => item.isSelected)
	},
	// 计算商品总数量
	totalCount(state) {
		return state.cartList.reduce((pre, shopItem) => {
			return pre += shopItem.isSelected ? shopItem.count : 0
		}, 0)
	},
	// 计算总价格
	totalPrice(state) {
		return state.cartList.reduce((pre, shopitem) => {
			return pre += shopitem.isSelected ? shopitem.count * shopitem.retailPrice : 0
		}, 0)
	},
	// 过滤选中的商品
	newCartList(state) {
		let newCartListArr = state.cartList.map(item => {
			return item.isSelected ? item : null
		})
		let filterCartList = newCartListArr.filter(item => {
			return item != null
		})
		return filterCartList
	}

}

export default {
	state,
	mutations,
	actions,
	getters
}
